package com.xinjie.www.servlet;

import com.xinjie.www.po.User;
import com.xinjie.www.service.collect.CollectServiceImpl;
import com.xinjie.www.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CollectServlet extends HttpServlet {
    CollectServiceImpl collectService = new CollectServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("do".equals(method)){
            this.doCollcet(req,resp);
        }
        if ("cancel".equals(method)){
            try {
                this.cancelCollcet(req,resp);
            } catch (SQLException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    private void doCollcet(HttpServletRequest req, HttpServletResponse resp) {
        int postId = Integer.parseInt(req.getParameter("postId"));
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        User user = (User) o;
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sdf.format(date);
        try {
            boolean b = collectService.doCollect(postId, user.getUserId(), time);
            if (b) {
                req.getSession().setAttribute("CollectSuccess", "收藏成功");
                resp.sendRedirect("/UserPage/PostList.jsp");
            } else {
                req.getSession().setAttribute("CollectLose", "收藏失败");
                resp.sendRedirect("/UserPage/PostList.jsp");
            }
        } catch (SQLException | ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }
    }

    private void cancelCollcet(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ClassNotFoundException, IOException {
        int collectId = Integer.parseInt(req.getParameter("collectId"));
        boolean b = collectService.cancelCollect(collectId);
        if (b){
            req.getSession().setAttribute("cancelSuccess","取消成功");
            resp.sendRedirect("/UserPage/CollectList.jsp");
        }else {
            req.getSession().setAttribute("cancelLose","取消失败");
            resp.sendRedirect("/UserPage/CollectList.jsp");
        }
    }
}
